//
//  ACWebProgressLayer.m
//  ACFramework
//
//  Created by caoyq on 2017/7/29.
//

#import "ACWebProgressLayer.h"
#import <UIKit/UIKit.h>
@class NSTimer;

static NSTimeInterval const kTimeInterval = 0.008;

@implementation ACWebProgressLayer
{
    NSTimer *_timer;
    CGFloat _plusWidth; //宽度增加量
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    
    self.lineWidth = 2;
    self.progressColor = [UIColor blueColor];
    self.strokeColor = self.progressColor.CGColor;
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:kTimeInterval target:self selector:@selector(pathChange:) userInfo:nil repeats:YES];
    [_timer pause];
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 2)];
    [path addLineToPoint:CGPointMake([UIScreen mainScreen].bounds.size.width, 2)];
    
    self.path = path.CGPath;
    self.strokeEnd = 0;
}

#pragma mark - setter

- (void)setProgressColor:(UIColor *)progressColor {
    if (progressColor != nil) {
        _progressColor = progressColor;
        self.strokeColor = self.progressColor.CGColor;
    }
}

#pragma mark - public methods

- (void)startLoad {
    //状态栏的网络网络加载loading
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [_timer resume];
    self.hidden = NO;
    _plusWidth = 0.01;
}

- (void)finishedLoad {
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [_timer pause];
    self.strokeEnd = 1.0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.hidden = YES;
        self.strokeEnd = 0;
    });
}

- (void)destory {
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [_timer invalidate];
    _timer = nil;
    self.hidden = YES;
    [self removeFromSuperlayer];
}

#pragma mark - action

- (void)pathChange: (NSTimer *)timer {
    self.strokeEnd += _plusWidth;
    
    if (self.strokeEnd > 0.8) {
        if (self.strokeEnd > 0.9) {
            _plusWidth = 0;
        }else {
            _plusWidth = 0.001;
        }
    }
}

@end

//////////////NSTimer Category

@implementation NSTimer (progress)

- (void)pause {
    if (self.isValid) {
        [self setFireDate:[NSDate distantFuture]];
    }
}

- (void)resume {
    if (self.isValid) {
        [self setFireDate:[NSDate date]];
    }
}

@end
